package www.dianbaozu.com.ui.chat.friend.holder

import android.view.View
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import com.bumptech.glide.Glide
import com.netease.nim.uikit.R
import com.netease.nim.uikit.api.NIMHelper
import com.netease.nim.uikit.business.uinfo.UserInfoHelper
import com.netease.nim.uikit.common.ui.recyclerview.adapter.BaseQuickAdapter
import com.netease.nim.uikit.common.ui.recyclerview.holder.BaseViewHolder
import com.netease.nim.uikit.common.ui.recyclerview.holder.RecyclerViewHolder
import com.netease.nim.uikit.databinding.ItemFriendsBinding
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo
import www.wen.com.common.lib.data.entities.FriendEntity
import www.wen.com.common.lib.extension.glide.setImageUrl

class FriendUserViewHolder(baseQuickAdapter: BaseQuickAdapter<FriendEntity, BaseViewHolder>) :
    RecyclerViewHolder<BaseQuickAdapter<FriendEntity, BaseViewHolder>, BaseViewHolder, FriendEntity>(
        baseQuickAdapter
    ) {
    private var binding: ItemFriendsBinding? = null

    override fun convert(
        holder: BaseViewHolder,
        data: FriendEntity,
        position: Int,
        isScrolling: Boolean
    ) {
        data.friend?.let {
            binding = DataBindingUtil.bind(holder.itemView)
            binding?.apply {
                tvSubtitle.visibility = View.GONE
                slUnreadMessage.visibility = View.GONE
                imgArrow.visibility = View.GONE
                imgOnlineStatus.visibility = View.VISIBLE

                val offlineFirstPosition = 2 + data.onlineFriendsCount

                tvTopStatus.isVisible = position == 2 || position == offlineFirstPosition
                tvTopStatus.text =
                    if (position < offlineFirstPosition) "在线-${data.onlineFriendsCount}" else "离线-${data.offlineFriendsCount}"

                ivAvatar.loadBuddyAvatar(it.account)
                tvTitle.text = UserInfoHelper.getUserTitleName(it.account, SessionTypeEnum.P2P)
                NIMHelper.fetchUserInfo(mutableListOf(it.account),object :
                    RequestCallback<List<NimUserInfo>> {
                    override fun onSuccess(param: List<NimUserInfo>?) {
                        tvTitle.text = param?.get(0)?.name
                    }

                    override fun onFailed(code: Int) {
                    }

                    override fun onException(exception: Throwable?) {
                    }
                })

                imgOnlineStatus.setImageResource(if (NIMHelper.accountIsOnline(it.account))
                    R.drawable.ic_circle_green_middle_1 else
                    R.drawable.ic_circle_gray_middle_1)

            }
        }
    }
}